package com.example.covid19_confirmed_global.controllers;

import com.example.covid19_confirmed_global.models.RegionStats;
import com.example.covid19_confirmed_global.services.CoronaVirusDataService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class Homecontrollers {

    private final CoronaVirusDataService coronaVirusDataService;

    public Homecontrollers(CoronaVirusDataService coronaVirusDataService){
        this.coronaVirusDataService = coronaVirusDataService;
    }

    @GetMapping("/{country}")
    public String home(Model model,@PathVariable("country") String country){
        List<RegionStats> allStats;
        if(country == null || country.equals("all"))
            allStats = coronaVirusDataService.getAllRegionStats();
        else
            allStats = coronaVirusDataService.getAllRegionStats()
                    .parallelStream()
                    .filter(locationsStats -> locationsStats.getCountry().equals(country))
                    .collect(Collectors.toUnmodifiableList());


        model.addAttribute("country",country);
        int totalReportedCases = allStats.parallelStream().mapToInt(RegionStats::getLatestTotalCases).sum();
        int totalNewCases = allStats.parallelStream().mapToInt(RegionStats::getDiffFromPrevDay).sum();

        model.addAttribute("regionStats",allStats);
        model.addAttribute("totalReportedCases",totalReportedCases);
        model.addAttribute("totalNewCases",totalNewCases);
        model.addAttribute("localDateTime", LocalDateTime.now());
        return "index";

    }
}
